<?php

namespace app\admin\controller;

use app\admin\validate\ThumbValidate;
use app\service\ThumbService;
use think\exception\ValidateException;

class Thumb extends Admin
{
    public function __construct(ThumbService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    private function save()
    {
        $params = $this->request->Post();
        $data = [
            "link_url" => $params["link_url"],
            "thumb" => $params["thumb"],
            "id" => $params["id"] ?? 0,
            "sort" => $params["sort"],
            "remark" => $params["remark"],
            "position" => $params["position"],
        ];
        $action = $this->request->action();
        try {
            validate(ThumbValidate::class)->scene($action)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->save($data);
        if ($ret) {
            $this->success("操作成功");
        } else {
            $this->error("保存失败");
        }
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "缩略图列表");
            return $this->fetch("index");
        }
        $params = $this->request->post();
        $where = [];
        if (!empty($params["status"])) {
            $where["status"] = $params["status"];
        }
        $ret = $this->service->getList($where, "*");
        $this->result($ret);
    }

    public function add()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "添加缩略图");
            $this->assign("vo", null);
            return $this->fetch("form");
        }
        $this->save();
    }

    public function edit()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "编辑缩略图");
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $vo = $this->service->get($id);
            if (empty($vo)) {
                throw new ValidateException("不存在对应的缩略图");
            }
            $this->assign("vo", $vo);
            return $this->fetch("form");
        }
        $this->save();
    }

    public function setStatus()
    {
        $params = $this->request->Post();
        try {
            validate(ThumbValidate::class)->scene("status")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $vo = $this->service->get($params["id"], ["id"]);
        if (empty($vo)) {
            throw new ValidateException("不存在对应缩略图");
        }
        $data["id"] = $params["id"];
        $data["status"] = $params["status"];
        $ret = $this->service->save($data);
        if ($ret) {
            $this->success("操作成功");
        } else {
            $this->error("保存失败");
        }
    }
}